package com.lyj.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.lyj.model.Admin;
import com.lyj.model.User;

/**
* 
* @author 李艺江
* @version 创建时间：2019年5月7日 上午10:13:56
*/

@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends BaseAction<Object> {

	private static final long serialVersionUID = 1L;
	
	public String login() {
		HttpServletRequest hsRequest = ServletActionContext.getRequest();
		String idStr = (String)hsRequest.getParameter("id");
        Integer id = 0;
        if(idStr.equals("")) {
        	id = 0;
        }else {
        	id= Integer.parseInt(idStr);
        }
        String password = (String)hsRequest.getParameter("pwd");
        Integer role = Integer.parseInt((String)hsRequest.getParameter("role"));
        if(id == 0 || id == null) {
        	request.put("nameerr", "用户名不能为空!");
            if(password.equals("") || password == null) {
        	    request.put("pwderr", "密码不能为空!");
        	    return "reLogin";
            }
            return "reLogin";
        }
        if(role == 1) {
        	User user = new User();
        	user.setId(id);
        	user.setPassword(password);
        	user = userService.login(user);
        	if(user == null) {
            	request.put("loginerr", "用户名或密码错误!");
        		return "reLogin";
        	}
        	session.put("user", user);
        	return "userLogin";
        }
        if(role == 2) {
        	Admin admin = new Admin();
        	admin.setId(id);
        	admin.setPassword(password);
        	admin = adminService.login(admin);
        	if(admin == null) {
            	request.put("loginerr", "用户名或密码错误!");
        		return "reLogin";
        	}
        	session.put("admin", admin);
        	return "adminLogin";
        }
        return ERROR;
	}

	public String logout() {
		if(session.get("user") != null) {
			session.remove("user");
		}
		if(session.get("admin") != null) {
			session.remove("admin");
		}
		return "reLogin";
	}
}
